from flask import request

from App.Api import Api
from App.Common.I18n import I18n
from App.Common.JwtClass import JwtClass


@Api.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        data = request.form
        username = data.get("username")
        password = data.get("password")
        # 验证账号密码，正确则返回token，用于后续接口权限验证
        # TODO 通过数据库查询 判断用户名和密码是否正确
        uid = 0
        if username == "root" and password == "123456":
            userinfo = loginSuccess(uid)
            return userinfo
        else:
            return [], 1010, I18n.lang("login_fail", "en")
    else:
        return [], 1010, I18n.lang("login_fail", "en")


# 登录成功, 设置token 过期时间 返回用户信息
def loginSuccess(uid):
    # TODO 通过uid查询需要存入token的字段
    userinfo = {"id": 1, "username": "username"}
    token, time = JwtClass.create_token(userinfo)
    userinfo["token"] = token
    # TODO 修改用户表中的token过期时间 记录用户token
    return userinfo
